package drafts_config

import (
	"encoding/json"
	"errors"
	"news_for_deepseek_interface/logger"
	"news_for_deepseek_interface/model"
	"news_for_deepseek_interface/model/drafts"
	"news_for_deepseek_interface/project/rabbitmq"
	"strconv"
	"strings"
	"time"
)

type ProduceNewsMessage struct {
	KeepTitle          int
	KeepContent        int
	StartId            int
	Number             int
	TypeClassifyId     int
	BusinessClassifyId int
	Ids                []int
	Type               int
}

// 创建日志
func (p *ProduceNewsMessage) createLog() (id int, err error) {
	db := model.GetInstance().DB

	var idsStr = ""
	for _, id := range p.Ids {
		idsStr += strconv.Itoa(id) + ","
	}

	idsStr = strings.Trim(idsStr, ",")

	// 创建记录并获取ID
	draftsLogsModel := drafts.DraftsLogsModel{
		KeepTitle:          p.KeepTitle,
		KeepContent:        p.KeepContent,
		TypeClassifyId:     p.TypeClassifyId,
		BusinessClassifyId: p.BusinessClassifyId,
		Date:               time.Now(),
		TotalNum:           len(p.Ids),
		Ids:                idsStr,
		Type:               p.Type,
		CreatedAt:          time.Now(),
		UpdatedAt:          time.Now(),
	}

	if err = db.Create(&draftsLogsModel).Error; err != nil {
		return 0, err
	}

	return draftsLogsModel.Id, nil
}

// 根据条件抽取id
func (p *ProduceNewsMessage) getIds() (ids []int, err error) {

	where := map[string]interface{}{}

	if p.TypeClassifyId != 0 {
		where["type_classify_id"] = p.TypeClassifyId
	}

	if p.BusinessClassifyId != 0 {
		where["business_classify_id"] = p.BusinessClassifyId
	}

	if err = model.GetInstance().DB.Debug().
		Model(&model.QuestionAnswerModel{}).
		Where(where).
		Where("id >= ?", p.StartId).
		Order("id asc").
		Limit(p.Number).
		Pluck("id", &ids).Error; err != nil {
		return
	}

	return
}

// 生成文章
func (p *ProduceNewsMessage) GenerateNews() (err error) {

	//取执行的知识库id
	ids, err := p.getIds()
	if err != nil {
		return err
	}

	//取最后id
	lastId := ids[len(ids)-1] + 1

	//判断是否是最后一条
	var questionAnswer model.QuestionAnswerModel
	model.GetInstance().DB.Model(&model.QuestionAnswerModel{}).Order("id DESC").First(&questionAnswer)
	if lastId > questionAnswer.Id {
		lastId = 0
	}

	//更新最后id
	model.GetInstance().DB.Model(&drafts.DraftsConfigModel{}).
		Debug().
		Where("id = ?", 1).
		Updates(
			map[string]interface{}{
				"start_id":   lastId,
				"updated_at": time.Now(),
			},
		)

	//需要生产的知识库id
	p.Ids = ids

	if len(ids) == 0 {
		return errors.New("没有匹配的知识库记录,无法生成文章")
	}

	id, err := p.createLog()
	if err != nil {
		logger.Error("创建生成文章记录失败：" + err.Error())
		return err
	}

	message := rabbitmq.NewsMessage{
		KeepTitle:   p.KeepTitle,
		KeepContent: p.KeepContent,
		Ids:         ids,
		LogId:       id,
	}

	messageBytes, err := json.Marshal(message)
	if err != nil {
		logger.Error("发送生成文章序列化消息失败：" + err.Error())
		return err
	}

	// 发送消息到 RabbitMQ
	if err := rabbitmq.Publish(
		rabbitmq.NewsConfig.ExchangeName,
		rabbitmq.NewsConfig.RoutingKey,
		messageBytes,
	); err != nil {
		logger.Error("发送生成文章MQ消息失败：" + err.Error())
		return err
	}

	return nil
}
